import os
import sys

# 添加项目根目录到Python路径，以便导入config_reader模块
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
sys.path.append(project_root)

from config_reader import get_deepseek_api_key, get_openai_api_key, get_ollama_host, get_milvus_config
from mem0 import Memory

# 从配置文件读取API密钥和配置
deepseek_api_key = get_deepseek_api_key()
openai_api_key = get_openai_api_key()
ollama_host = get_ollama_host()
milvus_config = get_milvus_config()

# 设置环境变量
os.environ["DEEPSEEK_API_KEY"] = deepseek_api_key
os.environ["OPENAI_API_KEY"] = openai_api_key
os.environ["OLLAMA_HOST"] = ollama_host

# 构建配置字典
config = {
    "vector_store": {
        "provider": "milvus",
        "config": {
            "collection_name": milvus_config['collection_name'],
            "embedding_model_dims": milvus_config['embedding_model_dims'],
            "url": milvus_config['url'],
            "token": milvus_config['token'],
        }
    },
    "llm": {
        "provider": "deepseek",
        "config": {
            "model": "deepseek-chat",
            "temperature": 0.2,
            "max_tokens": 2000,
            "top_p": 1.0
        }
    },
    "embedder": {
        "provider": "ollama",
        "config": {
            "model": "mxbai-embed-large",
            "ollama_base_url": ollama_host
        }
    }
}

def test_memory_setup():
    """测试 Memory 设置"""
    try:
        print("正在初始化 Memory...")
        m = Memory.from_config(config)
        print("Memory 初始化成功！")
        
        messages = [
            {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
            {"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
            {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
            {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
        ]
        
        print("正在添加消息到记忆...")
        m.add(messages, user_id="alice", metadata={"category": "movies"})
        print("消息添加成功！")
        
        # 测试查询
        print("正在测试查询...")
        results = m.query("What kind of movies does the user like?", user_id="alice")
        print(f"查询结果：{results}")
        
        # 测试记忆检索
        print("\n正在测试记忆检索...")
        retrieved_messages = m.get(user_id="alice", limit=5)
        print(f"检索到的消息数量：{len(retrieved_messages)}")
        for i, msg in enumerate(retrieved_messages):
            print(f"消息 {i+1}: {msg['content'][:100]}...")
            
        return True
        
    except Exception as e:
        print(f"错误：{e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    test_memory_setup()
